import React, { useState, useEffect, useRef } from "react";

interface IntegratedAIProps {
    isOpen: boolean;
    onClose: () => void;
}

interface Message {
    type: "user" | "ai";
    content: string;
    isVoice?: boolean;
}

const IntegratedAI: React.FC<IntegratedAIProps> = ({ isOpen, onClose }) => {
    const [messages, setMessages] = useState<Message[]>([
        {
            type: "ai",
            content: "你好！我是小维AI助手，支持文字和语音交互。请开始对话吧！",
        },
    ]);
    const [input, setInput] = useState("");
    const [isListening, setIsListening] = useState(false);
    const [isSpeaking, setIsSpeaking] = useState(false);
    const [activeTab, setActiveTab] = useState<"chat" | "voice">("chat");
    const [isLoading, setIsLoading] = useState(false);
    const recognitionRef = useRef<any>(null);
    const synthesisRef = useRef<SpeechSynthesis | null>(null);

    // 初始化语音识别
    useEffect(() => {
        if (
            typeof window !== "undefined" &&
            "webkitSpeechRecognition" in window
        ) {
            // 主要语音识别
            recognitionRef.current = new (
                window as any
            ).webkitSpeechRecognition();
            recognitionRef.current.continuous = false;
            recognitionRef.current.interimResults = false;
            recognitionRef.current.lang = "zh-CN";

            recognitionRef.current.onstart = () => {
                setIsListening(true);
            };

            recognitionRef.current.onresult = (event: any) => {
                const transcript = event.results[0][0].transcript;
                setInput(transcript);
                handleSendMessage(transcript, true);
            };

            recognitionRef.current.onend = () => {
                setIsListening(false);
            };

            recognitionRef.current.onerror = (event: any) => {
                console.error("语音识别错误:", event.error);
                setIsListening(false);
            };
        }

        synthesisRef.current = window.speechSynthesis;
    }, []);

    const startListening = () => {
        if (recognitionRef.current) {
            recognitionRef.current.start();
        }
    };

    const stopListening = () => {
        if (recognitionRef.current) {
            recognitionRef.current.stop();
        }
    };

    const speak = (text: string) => {
        if (synthesisRef.current) {
            setIsSpeaking(true);
            const utterance = new SpeechSynthesisUtterance(text);
            utterance.lang = "zh-CN";
            utterance.rate = 0.9;
            utterance.pitch = 1.1;

            utterance.onend = () => {
                setIsSpeaking(false);
            };

            synthesisRef.current.speak(utterance);
        }
    };

    // 调用后端AI接口
    const callAIBackend = async (message: string): Promise<string> => {
        try {
            const response = await fetch("http://localhost:8000/chat", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    message: message,
                    type: activeTab === "voice" ? "voice" : "text",
                }),
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            return (
                data.response ||
                data.message ||
                "抱歉，我现在无法回答您的问题。"
            );
        } catch (error) {
            console.error("AI后端调用失败:", error);
            throw new Error("无法连接到AI后台服务，请检查服务器状态");
        }
    };

    const handleSendMessage = async (
        messageText?: string,
        isVoiceInput?: boolean
    ) => {
        const text = messageText || input;
        if (!text.trim()) return;

        // 添加用户消息
        const userMessage: Message = {
            type: "user",
            content: text,
            isVoice: isVoiceInput,
        };
        setMessages((prev) => [...prev, userMessage]);

        setIsLoading(true);
        setInput("");

        try {
            // 调用后端AI接口
            const aiResponse = await callAIBackend(text);

            const aiMessage: Message = {
                type: "ai",
                content: aiResponse,
                isVoice: activeTab === "voice",
            };
            setMessages((prev) => [...prev, aiMessage]);

            // 如果是语音模式，自动播放回复
            if (activeTab === "voice") {
                speak(aiResponse);
            }
        } catch (error) {
            console.error("发送消息失败:", error);
            const errorMessage: Message = {
                type: "ai",
                content:
                    error instanceof Error
                        ? error.message
                        : "抱歉，我现在无法回答您的问题，请稍后再试。",
                isVoice: false,
            };
            setMessages((prev) => [...prev, errorMessage]);
        } finally {
            setIsLoading(false);
        }
    };

    const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === "Enter" && !isLoading) handleSendMessage();
    };

    if (!isOpen) return null;

    return (
        <div
            style={{
                position: "fixed",
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: "rgba(0,0,0,0.8)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                zIndex: 1000,
            }}
        >
            <div
                style={{
                    width: "90%",
                    maxWidth: 700,
                    height: "85%",
                    backgroundColor: "#fff",
                    borderRadius: 20,
                    display: "flex",
                    flexDirection: "column",
                    overflow: "hidden",
                    boxShadow: "0 20px 60px rgba(0,0,0,0.3)",
                }}
            >
                {/* 对话框头部 */}
                <div
                    style={{
                        padding: "20px 24px",
                        borderBottom: "1px solid #e0e0e0",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "space-between",
                        background:
                            "linear-gradient(90deg, #667eea 0%, #764ba2 100%)",
                        color: "#fff",
                    }}
                >
                    <div
                        style={{
                            display: "flex",
                            alignItems: "center",
                            gap: 12,
                        }}
                    >
                        <span
                            role="img"
                            aria-label="AI"
                            style={{ fontSize: 24 }}
                        >
                            🤖
                        </span>
                        <h3
                            style={{ margin: 0, fontSize: 20, fontWeight: 600 }}
                        >
                            小维AI智能助手
                        </h3>
                    </div>
                    <button
                        onClick={onClose}
                        style={{
                            background: "none",
                            border: "none",
                            color: "#fff",
                            fontSize: 24,
                            cursor: "pointer",
                            padding: 4,
                        }}
                    >
                        ✕
                    </button>
                </div>

                {/* 标签页切换 */}
                <div
                    style={{
                        display: "flex",
                        borderBottom: "1px solid #e0e0e0",
                        background: "#f8f9fa",
                    }}
                >
                    <button
                        onClick={() => setActiveTab("chat")}
                        style={{
                            flex: 1,
                            padding: "16px 24px",
                            border: "none",
                            background:
                                activeTab === "chat"
                                    ? "#667eea"
                                    : "transparent",
                            color: activeTab === "chat" ? "#fff" : "#666",
                            fontSize: 16,
                            fontWeight: 600,
                            cursor: "pointer",
                            transition: "all 0.3s ease",
                        }}
                    >
                        💬 文字聊天
                    </button>
                    <button
                        onClick={() => setActiveTab("voice")}
                        style={{
                            flex: 1,
                            padding: "16px 24px",
                            border: "none",
                            background:
                                activeTab === "voice"
                                    ? "#ff6b6b"
                                    : "transparent",
                            color: activeTab === "voice" ? "#fff" : "#666",
                            fontSize: 16,
                            fontWeight: 600,
                            cursor: "pointer",
                            transition: "all 0.3s ease",
                        }}
                    >
                        🎤 语音对话
                    </button>
                </div>

                {/* 消息列表 */}
                <div
                    style={{
                        flex: 1,
                        padding: "20px",
                        overflowY: "auto",
                        display: "flex",
                        flexDirection: "column",
                        gap: 16,
                    }}
                >
                    {messages.map((message, index) => (
                        <div
                            key={index}
                            style={{
                                display: "flex",
                                justifyContent:
                                    message.type === "user"
                                        ? "flex-end"
                                        : "flex-start",
                            }}
                        >
                            <div
                                style={{
                                    maxWidth: "70%",
                                    padding: "12px 16px",
                                    borderRadius: 18,
                                    backgroundColor:
                                        message.type === "user"
                                            ? "#e8f4fd"
                                            : "#f0f0f0",
                                    color:
                                        message.type === "user"
                                            ? "#000"
                                            : "#333",
                                    fontSize: 16,
                                    lineHeight: 1.4,
                                    border:
                                        message.type === "user"
                                            ? "1px solid #b3d9ff"
                                            : "1px solid #e0e0e0",
                                    position: "relative",
                                }}
                            >
                                {message.content}
                                {message.isVoice && (
                                    <span
                                        style={{
                                            position: "absolute",
                                            top: -8,
                                            right: -8,
                                            fontSize: 12,
                                            background: "#ff6b6b",
                                            color: "#fff",
                                            borderRadius: "50%",
                                            width: 20,
                                            height: 20,
                                            display: "flex",
                                            alignItems: "center",
                                            justifyContent: "center",
                                        }}
                                    >
                                        🎤
                                    </span>
                                )}
                            </div>
                        </div>
                    ))}
                    {isLoading && (
                        <div
                            style={{
                                display: "flex",
                                justifyContent: "flex-start",
                            }}
                        >
                            <div
                                style={{
                                    padding: "12px 16px",
                                    borderRadius: 18,
                                    backgroundColor: "#f0f0f0",
                                    color: "#666",
                                    fontSize: 16,
                                    display: "flex",
                                    alignItems: "center",
                                    gap: 8,
                                }}
                            >
                                <div style={{ display: "flex", gap: 4 }}>
                                    <div
                                        style={{
                                            width: 8,
                                            height: 8,
                                            borderRadius: "50%",
                                            background: "#667eea",
                                            animation:
                                                "bounce 1.4s infinite ease-in-out",
                                        }}
                                    ></div>
                                    <div
                                        style={{
                                            width: 8,
                                            height: 8,
                                            borderRadius: "50%",
                                            background: "#667eea",
                                            animation:
                                                "bounce 1.4s infinite ease-in-out 0.2s",
                                        }}
                                    ></div>
                                    <div
                                        style={{
                                            width: 8,
                                            height: 8,
                                            borderRadius: "50%",
                                            background: "#667eea",
                                            animation:
                                                "bounce 1.4s infinite ease-in-out 0.4s",
                                        }}
                                    ></div>
                                </div>
                                小维正在思考...
                            </div>
                        </div>
                    )}
                </div>

                {/* 输入区域 */}
                <div
                    style={{
                        padding: "20px",
                        borderTop: "1px solid #e0e0e0",
                        display: "flex",
                        gap: 12,
                        alignItems: "center",
                    }}
                >
                    {activeTab === "chat" ? (
                        <>
                            <input
                                type="text"
                                value={input}
                                onChange={(e) => setInput(e.target.value)}
                                onKeyDown={handleInputKeyDown}
                                placeholder="输入你的问题..."
                                disabled={isLoading}
                                style={{
                                    flex: 1,
                                    padding: "12px 16px",
                                    borderRadius: 25,
                                    border: "2px solid #e0e0e0",
                                    fontSize: 16,
                                    outline: "none",
                                    opacity: isLoading ? 0.6 : 1,
                                }}
                            />
                            <button
                                onClick={() => handleSendMessage()}
                                disabled={isLoading}
                                style={{
                                    padding: "12px 24px",
                                    borderRadius: 25,
                                    border: "none",
                                    background: isLoading
                                        ? "#ccc"
                                        : "linear-gradient(90deg, #667eea 0%, #764ba2 100%)",
                                    color: "#fff",
                                    fontSize: 16,
                                    fontWeight: 600,
                                    cursor: isLoading
                                        ? "not-allowed"
                                        : "pointer",
                                }}
                            >
                                {isLoading ? "发送中..." : "发送"}
                            </button>
                        </>
                    ) : (
                        <>
                            <input
                                type="text"
                                value={input}
                                onChange={(e) => setInput(e.target.value)}
                                onKeyDown={handleInputKeyDown}
                                placeholder="输入文字或点击麦克风说话..."
                                disabled={isLoading}
                                style={{
                                    flex: 1,
                                    padding: "12px 16px",
                                    borderRadius: 25,
                                    border: "2px solid #e0e0e0",
                                    fontSize: 16,
                                    outline: "none",
                                    opacity: isLoading ? 0.6 : 1,
                                }}
                            />
                            <button
                                onClick={
                                    isListening ? stopListening : startListening
                                }
                                disabled={isLoading}
                                style={{
                                    width: "50px",
                                    height: "50px",
                                    borderRadius: "50%",
                                    border: "none",
                                    background: isListening
                                        ? "linear-gradient(90deg, #ff6b6b 0%, #ee5a24 100%)"
                                        : isLoading
                                        ? "#ccc"
                                        : "linear-gradient(90deg, #667eea 0%, #764ba2 100%)",
                                    color: "#fff",
                                    fontSize: 20,
                                    cursor: isLoading
                                        ? "not-allowed"
                                        : "pointer",
                                    display: "flex",
                                    alignItems: "center",
                                    justifyContent: "center",
                                    animation: isListening
                                        ? "pulse 1s infinite"
                                        : "none",
                                }}
                            >
                                {isListening ? "⏹️" : "🎤"}
                            </button>
                            <button
                                onClick={() => handleSendMessage()}
                                disabled={isLoading}
                                style={{
                                    padding: "12px 24px",
                                    borderRadius: 25,
                                    border: "none",
                                    background: isLoading
                                        ? "#ccc"
                                        : "linear-gradient(90deg, #667eea 0%, #764ba2 100%)",
                                    color: "#fff",
                                    fontSize: 16,
                                    fontWeight: 600,
                                    cursor: isLoading
                                        ? "not-allowed"
                                        : "pointer",
                                }}
                            >
                                {isLoading ? "发送中..." : "发送"}
                            </button>
                        </>
                    )}
                </div>

                {/* 语音状态指示器 */}
                {(isListening || isSpeaking) && (
                    <div
                        style={{
                            position: "absolute",
                            top: "50%",
                            left: "50%",
                            transform: "translate(-50%, -50%)",
                            background: "rgba(0,0,0,0.8)",
                            color: "#fff",
                            padding: "20px 40px",
                            borderRadius: 20,
                            fontSize: 18,
                            fontWeight: 600,
                            zIndex: 1001,
                        }}
                    >
                        {isListening
                            ? "🎤 正在听你说话..."
                            : "🔊 小维正在说话..."}
                    </div>
                )}

                <style>{`
                    @keyframes pulse {
                        0% { transform: scale(1); }
                        50% { transform: scale(1.1); }
                        100% { transform: scale(1); }
                    }
                    
                    @keyframes bounce {
                        0%, 80%, 100% { transform: scale(0); }
                        40% { transform: scale(1); }
                    }
                `}</style>
            </div>
        </div>
    );
};

export default IntegratedAI;
